package com.iwhalecloud.bss.kite.cucc.service.attr.handler;

import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import com.iwhalecloud.bss.kite.service.attr.handler.AbstractAttrHandler;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;
import com.ztesoft.bss.common.util.ContextUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <Description> <br>
 *  协议月租
 * @author chen.cheng110<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2021年3月7日 <br>
 * @since R9.0<br>
 * @see com.iwhalecloud.bss.kite.cucc.service.attr.handler <br>
 */

public class AgreementMonthlyRentAttrHandler extends AbstractAttrHandler<KiteInst, AttrData> {
    @Autowired
    private IQuerySceneInstService querySceneInstService;
    @Autowired
    OperateInstAttrService operateInstAttrService;

    @Override
    public void before(KiteAttr attr, KiteInst inst, String value, AttrData data) {
        if (KiteStringUtils.isEmpty(value)) {
            return;
        }
        //  协议月租
        String check = "^(\\d|[1-9]\\d+)(\\.\\d+)?$";
        boolean isMatch = Pattern.matches(check, value);
        // 是否为页面初始化渲染，是（T），跳过校验
        String isInitPageRenderFlag = querySceneInstService.getExtParameterValue(data.getSceneInstId(), "isInitPageRenderFlag");
        if (!isMatch&& !KiteStringUtils.isEqual(isInitPageRenderFlag, LocalKeyConsts.IFTRUE_T)) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("协议月租输入不合法，必须大于等于0");
        }
    }
    @Override
    public void def(KiteAttr attr, KiteInst inst, AttrData data) {
        String sceneInstId = data.getSceneInstId();
        String custId = data.getCustId();
        Map<String, KiteAttr> offerAttr = inst.getAttrMap();
        List<KiteOfferInst> offerInstList = querySceneInstService.listMainOfferInsts(sceneInstId);
        //在这写联动处理
        String prodInstId = "";
        KiteProdInst kiteProdInst = null;
        if(KiteListUtils.isNotEmpty(offerInstList)){
            prodInstId = offerInstList.get(0).getInstId();
        }
        List<KiteProdInst> prodInstsFromMain = querySceneInstService.listProdInstsFromOfferInst(custId, prodInstId);
        if (KiteListUtils.isNotEmpty(prodInstsFromMain)) {
            kiteProdInst = prodInstsFromMain.get(0);
        }
        if(!KiteObjectUtils.isEmpty(kiteProdInst)
            &&!KiteObjectUtils.isEmpty(kiteProdInst.getAttrMap().get("200001970"))&&KiteStringUtils.equals("59", ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr())){
            if(KiteStringUtils.equalsAny(kiteProdInst.getAttrMap().get("200001970").getValue(),"100001378","100002793","100003447")){
                attr.setValue("0");
                attr.setValueDesc("0");
                attr.setIsEdit("F");
            }else{
                attr.setValue("");
                attr.setValueDesc("");
                attr.setIsEdit("T");
            }

        }
        //从prodInst里面获取attrMap的属性
        if(null!=kiteProdInst && KiteStringUtils.equals(kiteProdInst.getSpecId(),"1003538") && KiteMapUtils.isNotEmpty(kiteProdInst.getAttrMap())){//政务云信创产品
            Map<String, KiteAttr> kiteAttrMap = kiteProdInst.getAttrMap();
            List<DcPublic> dcPublicList = DcPublicCache.getByPcode("202110181536","offer_bbyz",inst.getSpecId());
            if(KiteListUtils.isNotEmpty(dcPublicList)){
                DcPublic dcPublic = dcPublicList.get(0);
                //获取业务属性
                KiteAttr ywsxAttr = kiteAttrMap.get(dcPublic.getCodeb());
                if(null!=ywsxAttr && KiteStringUtils.isNotBlank(ywsxAttr.getValue())){
                    if(KiteMapUtils.isNotEmpty(offerAttr) && !KiteStringUtils.equalsAny(ywsxAttr.getValue(),"0","0.0","0.00")){
                        if(null!=offerAttr.get("200001354")){
                            //获取产商品返回的标准月租的值
                            String bzyzValue = offerAttr.get("200001354").getDefaultValue();
                            if(KiteStringUtils.isNotBlank(bzyzValue)){
                                BigDecimal ywsxValueBd = new BigDecimal(ywsxAttr.getValue());
                                BigDecimal bzyzValueBd = new BigDecimal(bzyzValue);
                                BigDecimal attrValueBd = ywsxValueBd.multiply(bzyzValueBd);
                                String attrValueString = attrValueBd.setScale(2,BigDecimal.ROUND_HALF_DOWN).toString();
                                attr.setValue(attrValueString);
                                attr.setDefaultValue(attrValueString);
                                //根据标准月租和协议月租计算折扣
                                //标准月租
                                KiteAttr standardTariffsAttr = inst.getAttr("200001354");
                                KiteAttr discountAttr = inst.getAttr("200001352");
                                if (Objects.nonNull(discountAttr) && Objects.nonNull(standardTariffsAttr) && KiteStringUtils.isNotEmpty(standardTariffsAttr.getDefaultValue()) && KiteStringUtils.isNotEmpty(attr.getValue())) {
                                    BigDecimal agreedTariffsPrice = new BigDecimal(attr.getValue());
                                    BigDecimal standardTariffsPrice = new BigDecimal(standardTariffsAttr.getDefaultValue());
                                    Double discount = agreedTariffsPrice.divide(standardTariffsPrice, 4, BigDecimal.ROUND_HALF_UP).doubleValue();
                                    NumberFormat percent = NumberFormat.getPercentInstance();
                                    percent.setMaximumFractionDigits(4);
                                    percent.setGroupingUsed(false);
                                    String discountStr = KiteStringUtils.valueOf(percent.format(discount));
                                    //折扣
                                    operateInstAttrService.setAttrValue(inst, "200001352", discountStr, data.getSceneInstId(), null);
                                }
                            }
                        }
                    }
                }
            }
        }

    }

}
